package cn.com.cennavi.dataToTmc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import cn.com.cennavi.bean.DifPointTotalMapInfo;

import com.alibaba.fastjson.JSON;
import com.vividsolutions.jts.io.ParseException;

public class LaneDataToTMC {
	/** 北京地图数据 **/
	public static String laneMapData = "d:/data/beijingLaneMap.csv";
	/** 分车道数据 **/
	public static String laneData = "d:/data/lansimpleData.txt";
	public static HashMap<String, DifPointTotalMapInfo> mapId = new HashMap<String, DifPointTotalMapInfo>();
	public static HashMap<String, Integer> linkLenMap = new HashMap<String, Integer>();
	static DecimalFormat df = new DecimalFormat("##0.0");

	public static void init() throws ParseException, IOException {
		getMapId(laneMapData, linkLenMap, mapId);
		
	}

	private static void getMapId(String laneMapData2, HashMap<String, Integer> linkLenMap2, HashMap<String, DifPointTotalMapInfo> mapId2) throws ParseException, IOException {
		// TODO Auto-generated method stub
		// HashMap<String, DifPointTotalMapInfo> returnMap = new HashMap<String,
		// DifPointTotalMapInfo>();
		BufferedReader br = new BufferedReader(new FileReader(new File(laneMapData)));
		String line = "";
		while ((line = br.readLine()) != null) {
			DifPointTotalMapInfo difPointTotalMapInfo = DifPointTotalMapInfo.parseData1(line);
			if (difPointTotalMapInfo.roadClass == 0)
				continue;
			String linklen = difPointTotalMapInfo.linksLen;
			String[] arr = linklen.split("\\|");
			for (String s : arr) {
				String[] ss = s.split("\\:");
				String link = ss[0];
				int len = Integer.parseInt(ss[1]);
				linkLenMap2.put(link, len);
				// System.out.println("1111" + link + ":" + len);
			}
			String key = difPointTotalMapInfo.dif_Point_Id + "_" + difPointTotalMapInfo.straight_angle + "_" + difPointTotalMapInfo.flag;
			// System.out.println(key);
			if (mapId2.containsKey(key)) {
				// 可能一个方向有分叉的情况，这种情况下一个方向对应了多条link，会有重复key，属于正常现象
				// System.out.println(key);
				// System.out.println(line);

			} else {
				mapId2.put(key, difPointTotalMapInfo);
			}
		}

	}

	public static void main(String[] args) throws IOException, ParseException {
		// TODO Auto-generated method stub
		init();
		BufferedReader br = new BufferedReader(new FileReader(new File(laneData)));
		String line = "";
		while ((line = br.readLine()) != null) {
			LaneDataBean data = LaneDataBean.parseLine(line);
			try {
				ArrayList<String> dataList = transData(data);
				if (dataList != null)
					for (String laneData : dataList) {
						System.out.println(laneData);
					}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}

		}
	}

	private static ArrayList<String> transData(LaneDataBean data) {
		// TODO Auto-generated method stub
		ArrayList<String> datalist = new ArrayList<String>();
		String key = data.difPointId + "_" + data.straightAngle + "_" + data.trafficDir;
		DifPointTotalMapInfo laneMap = mapId.get(key);
		if (laneMap == null)
			return null;
		/**
		 * 解析地图数据
		 */
		String inlaneNoSeq = laneMap.inlaneNoSeq;
		String inlaneTurnFlag = laneMap.inlaneTurnFlag;
		if (inlaneTurnFlag == null) {
			System.out.println("turnFlag==null");
		}
		int inlinkNum = laneMap.inlinkNum;
		String enter_out_DifPoint_Link = laneMap.enter_out_DifPoint_Link;
		// 距离分歧点分段速度值
		String[] linkSeq = laneMap.linkArr.split("\\|");

		String inlinkid = enter_out_DifPoint_Link.split("\\|")[0];
		String outlinkid = enter_out_DifPoint_Link.split("\\|")[1];

		/*
		 * 解析lanedata
		 */
		String length_speed_seq_bef = data.length_speed_seq_bef;
		// 距离分歧点分段速度值
		String[] len_speedArr = length_speed_seq_bef.split("\\|");

		StringBuffer liksb = new StringBuffer();
		StringBuffer lensb = new StringBuffer();
		int len = 0;
		boolean isStart = false;
		for (int i = linkSeq.length - 1; i >= 0; i--) {
			String nowLink = linkSeq[i];
			if (isStart == true) {
				int nowLinkLen = linkLenMap.get(nowLink);
				len += nowLinkLen;
				liksb.append(nowLink);
				liksb.append("|");
				lensb.append(len);
				lensb.append("|");
			} else {
				if (nowLink.equals(outlinkid)) {
					isStart = true;
				}
			}
		}
		// 得到了分歧点前的link序列和link长度信息
		String[] liksbArr = liksb.toString().split("\\|");
		String[] lensbArr = lensb.toString().split("\\|");
		get(liksbArr, lensbArr, len_speedArr, laneMap, datalist);
		if (datalist.size() != 0) {
			return datalist;
		}
		return null;
	}

	/**
	 * 获取link部分路况信息
	 * 
	 * @param liksbArr
	 * @param lensbArr
	 * @param len_speedArr
	 * @param laneMap
	 * @param datalist
	 */
	private static void get(String[] liksbArr, String[] lensbArr, String[] len_speedArr, DifPointTotalMapInfo laneMap, ArrayList<String> datalist) {
		// TODO Auto-generated method stub
		/**
		 * 解析地图数据
		 */
		String inlaneNoSeq = laneMap.inlaneNoSeq;
		String inlaneTurnFlag = laneMap.inlaneTurnFlag;
		int inlinkNum = laneMap.inlinkNum;

		// 循环link序列，每个link去循环len_speedArr，当满足条件后输出一条link信息
		int[] secLenArr = getSecLenArr(len_speedArr);
		int[] linkLenArr = getLinkLenArr(lensbArr);

		int nowSecIndex = 0;
		int beforeLinkLen = 0;
		for (int i = 0; i < linkLenArr.length; i++) {
			JsonData json = new JsonData();
			String nowLinkId = liksbArr[i];
			int nowLinkLen = linkLenArr[i];
			int secNo = 1;
			boolean isOut = false;
			for (int j = nowSecIndex; j < secLenArr.length; j++) {
				int nowSecLen = secLenArr[j];
				double speed = (double) Integer.parseInt(len_speedArr[j].split("\\_")[1]);
				String nowSpeed = df.format(speed);
				if (nowLinkLen >= nowSecLen) {
					// 生成一个对象
					int SecLen = nowSecLen - beforeLinkLen;

					LaneLinkData lld = new LaneLinkData();
					Location location = new Location();
					Content content = new Content();
					Restriction restriction = new Restriction();

					location.linkid = nowLinkId;
					location.secNo = secNo + "";
					location.secLen = SecLen + "";

					content.speed = nowSpeed;

					restriction.laneRestriction = inlaneNoSeq;
					restriction.laneTotalNumber = inlinkNum + "";
					restriction.laneTurnFlag = inlaneTurnFlag;

					lld.content = content;
					lld.location = location;
					lld.restriction = restriction;
					json.LaneLinkData.add(lld);

					secNo++;
					// if ( json !=null) {
					// String jsonObject = JSON.toJSONString(json);
					// System.out.println("asd:" + jsonObject);
					// }
					continue;

				} else {
					// 这个时候，超过了一条link,从之前secLen到nowLinkLen全是当前speed，输出当前linkjson
					int SecLen = nowLinkLen - beforeLinkLen;
					// System.out.println("shuchu:");

					LaneLinkData lld = new LaneLinkData();
					Location location = new Location();
					Content content = new Content();
					Restriction restriction = new Restriction();

					location.linkid = nowLinkId;
					location.secNo = secNo + "";
					location.secLen = SecLen + "";

					content.speed = nowSpeed;

					restriction.laneRestriction = inlaneNoSeq;
					restriction.laneTotalNumber = inlinkNum + "";
					restriction.laneTurnFlag = inlaneTurnFlag;

					lld.content = content;
					lld.location = location;
					lld.restriction = restriction;
					json.LaneLinkData.add(lld);

					// 将secno逆序表示
					List<LaneLinkData> list = json.LaneLinkData;
					int sz = list.size();
					for (LaneLinkData d : list) {
						int nowNo = sz + 1 - Integer.parseInt(d.location.secNo);
						d.location.secNo = nowNo + "";
					}
					Collections.reverse(json.LaneLinkData);
					String jsonObject = JSON.toJSONString(json);
					// System.out.println(jsonObject);
					datalist.add(jsonObject);
					// 记录当前sec位置，下条link从此处开始循环
					isOut = true;
					json = null;
					nowSecIndex = j;
					beforeLinkLen = nowLinkLen;
					break;
				}

			}
			if (isOut == false) {
				List<LaneLinkData> list = json.LaneLinkData;
				int sz = list.size();
				for (LaneLinkData d : list) {
					int nowNo = sz + 1 - Integer.parseInt(d.location.secNo);
					d.location.secNo = nowNo + "";
				}
				Collections.reverse(json.LaneLinkData);
				String jsonObject = JSON.toJSONString(json);
				datalist.add(jsonObject);
				// System.out.println(jsonObject);
			}
		}
	}

	private static int[] getLinkLenArr(String[] lensbArr) {
		// TODO Auto-generated method stub
		int n = lensbArr.length;
		int[] lklenArr = new int[n];
		int sum = 0;
		for (int k = 0; k < n; k++) {
			// sum += Integer.parseInt(lensbArr[k]);
			lklenArr[k] = Integer.parseInt(lensbArr[k]);
		}
		return lklenArr;
	}

	private static int[] getSecLenArr(String[] len_speedArr) {
		// TODO Auto-generated method stub
		int n = len_speedArr.length;
		int[] disSpeedArr = new int[n];
		int sum = 0;
		for (int k = 0; k < n; k++) {
			String[] a = len_speedArr[k].split("\\_");
			sum += Integer.parseInt(a[0]);
			disSpeedArr[k] = sum;
		}
		return disSpeedArr;

	}

}